package com.zxc.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxc.common.dto.LoginDto;
import com.zxc.common.dto.RegisterDto;
import com.zxc.common.enums.LoginAndRegisterEnum;
import com.zxc.common.enums.NumberEnum;
import com.zxc.common.enums.ZxcCommonEnum;
import com.zxc.common.lang.Result;
import com.zxc.entity.User;
import com.zxc.entity.wechat.PersonInfo;
import com.zxc.service.UserService;
import com.zxc.service.wechat.WechatAuthService;
import com.zxc.util.DesUtil;
import com.zxc.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户账号controller
 */
@RestController
public class AccountController {

    @Autowired
    private UserService userService;
    @Autowired
    private WechatAuthService wechatAuthService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) {
        //1、判断是否为微信登录
        String roleType = (String) request.getAttribute("role_type");
        String state = (String) request.getAttribute("state");
        String openId = (String) request.getAttribute("openId");
        if (ObjectUtils.isEmpty(roleType) && ObjectUtils.isEmpty(state)) {
            User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
            if (ObjectUtils.isEmpty(user)) {
                user = userService.getOne(new QueryWrapper<User>().eq("phone_number", loginDto.getUsername()));
            }
            Assert.notNull(user, "用户不存在");
            if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
                return Result.fail("密码不正确");
            }
            String jwt = jwtUtils.generateToken(user.getId());
            response.setHeader("Authorization", jwt);
            response.setHeader("Access-control-Expose-Headers", "Authorization");

            return Result.succ(MapUtil.builder()
                    .put("id", user.getId())
                    .put("username", user.getUserName())
                    .put("avatar", user.getAvatar())
                    .put("email", user.getEmail())
                    .map()
            );
        } else {
            if ("wechat".equals(state) && "wechat".equals(DesUtil.getDecryptMessageStr(roleType)) && !ObjectUtils.isEmpty(openId)) {
                System.out.println("openId为===" + DesUtil.getDecryptMessageStr(openId));
                //根据openId查询用户信息
                PersonInfo personInfo = wechatAuthService.getOne(new QueryWrapper<PersonInfo>().eq("open_id", DesUtil.getDecryptMessageStr(openId)));
                System.out.println("登录用户信息=" + personInfo);
                String jwt = jwtUtils.generateToken(personInfo.getOpenId());
                response.setHeader("Authorization", jwt);
                response.setHeader("Access-control-Expose-Headers", "Authorization");
                return Result.succ(MapUtil.builder()
                        .put("id", personInfo.getOpenId())
                        .put("username", personInfo.getName())
                        .put("avatar", personInfo.getProfileImg())
                        .put("email", personInfo.getEmail())
                        .map()
                );
            } else {
                return Result.fail("登录失败");
            }
        }
    }

    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDto registerDto, HttpServletResponse response) {
        Result result = userService.register(registerDto);
        if (NumberEnum.TWO_HUNDRED.getKey().equals(result.getCode())) {
            RegisterDto userInfo = (RegisterDto) result.getData();
            String jwt = jwtUtils.generateToken(userInfo.getId());
            response.setHeader("Authorization", jwt);
            response.setHeader("Access-control-Expose-Headers", "Authorization");
            return Result.succ(MapUtil.builder()
                    .put("id", userInfo.getId())
                    .put("username", userInfo.getUserName())
                    .put("avatar", userInfo.getAvatar())
                    .put("email", userInfo.getEmail())
                    .map()
            );
        }
        return result;

    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }

}
